package by.sjc.grsu.web.controller;

import by.sjc.grsu.model.Account;
import by.sjc.grsu.model.Periodical;
import by.sjc.grsu.model.Subscription;
import by.sjc.grsu.security.CustomUserDetails;
import by.sjc.grsu.service.PeriodicalsService;
import by.sjc.grsu.service.SubscriptionsService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/subs")
public class SubscriptionsController {
    public static final Logger logger = Logger.getLogger(SubscriptionsController.class);

    @Autowired
    private SubscriptionsService subscriptionsService;
    @Autowired
    private PeriodicalsService periodicalsService;

    @PreAuthorize("isFullyAuthenticated()")
    @RequestMapping(value = "/list")
    public ModelAndView listSubscriptions(Authentication authentication) {
        Account account = ((CustomUserDetails) authentication.getPrincipal()).getAccount();
        logger.info("account = "+account);
        List<Subscription> subscriptions = subscriptionsService.getAccountSubscriptions(account);

        ModelAndView mav = new ModelAndView("subscription/list");
        mav.addObject("subscriptions", subscriptions);
        return mav;
    }

    @PreAuthorize("isFullyAuthenticated()")
    @RequestMapping(value = "/disable")
    public ModelAndView disableSubscription(
                @RequestParam("subId") int subId ) {
        subscriptionsService.disableSubscription(subId);
        ModelAndView mav = new ModelAndView("redirect:/subs/list");
        return mav;
    }
}
